/* --------------------------
 * Pebble Autoconfig
 * --------------------------
*/
PConfig.init();

/* Initialize all range sliders */
var numberElements = document.querySelectorAll('input[type="number"]');

for ( var i = 0; i < numberElements.length; i++ ) {
	var parent = findParentByClassName(numberElements[i], "pure-g");
	var node = parent.querySelector('input[type="range"]');
	node.value = numberElements[i].value;
}

/* --------------------------
 * Helpers
 * --------------------------
*/

if( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {
	var element = document.querySelector("header");
	element.parentNode.removeChild(element);
}

function findParentByClassName(node, className) {
	if (node.classList.contains(className)) {
		return node;
	} else {
		if (node.parentNode != null) {
			return findParentByClassName(node.parentNode, className);
		} else {
			return null;
		}
	}
}

function log (text) {
	{%- if preferences["debug"] %}
	var logdiv = document.getElementById("log");
	logdiv.innerHTML = text + "<br>" + logdiv.innerHTML;
	console.log(text);
	{%- endif %}
}

/* --------------------------
 * Number + Range
 * --------------------------
*/

if(document.querySelector('input[type="number"]') != null) {
	document.querySelector('input[type="number"]').addEventListener('blur', function (event) {
		var parent = findParentByClassName(this, "pure-g");
		var node = parent.querySelector('input[type="range"]');
		node.value = this.value;
	});

	document.querySelector('input[type="range"]').addEventListener('change', function (event) {
		var parent = findParentByClassName(this, "pure-g");
		var node = parent.querySelector('input[type="number"]');
		node.value = this.value;
	});
}

/* --------------------------
 * Buttons
 * --------------------------
*/

document.getElementById("save").addEventListener("click", function (event) {
	log("Save clicked");
	var form = document.querySelector("form");
	if (form.checkValidity() && form.checkValidityAndroid()) {
		location.href = 'pebblejs://close#' + encodeURIComponent(JSON.stringify(PConfig.getFormValues()));
	}
	event.preventDefault();
});

document.getElementById('cancel').addEventListener('click', function (event) {
	event.preventDefault();
	log("Cancel clicked");
	location.href = 'pebblejs://close#';
	
});

/* --------------------------
 * Debug
 * --------------------------
*/
log("User-agent: " + navigator.userAgent );
